﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;
using System.Web;

namespace YouTubeStormer
{
    class Communications
    {
        public static string YoutubeBareHostUrl =               "www.youtube.com";
        public static string YoutubeWatchUrl =                  "http://www.youtube.com/watch?v=";
        public static string YoutubeBaseUrl =                   "http://www.youtube.com/";
        public static string YoutubeAuthenticationUrl =         "https://www.google.com/accounts/ServiceLoginAuth?service=youtube";
        public static string YoutubePreAuthenticationUrl =      "https://www.google.com/accounts/ServiceLogin?uilel=3&service=youtube&passive=true&continue=http%3A%2F%2Fwww.youtube.com%2Fsignin%3Faction_handle_signin%3Dtrue%26nomobiletemp%3D1%26hl%3Den_US%26next%3D%252F&hl=en_US&ltmpl=sso";
        public static string YoutubeCheckCookieUrl =            "https://www.google.com/accounts/CheckCookie?continue=http%3A%2F%2Fwww.youtube.com%2Fsignin%3Faction_handle_signin%3Dtrue%26nomobiletemp%3D1%26hl%3Den_US%26next%3D%252Findex&hl=en_US&service=youtube&ltmpl=sso&chtml=LoginDoneHtml";
        public static string YoutubeLoginAuthorizationUrl =     "http://www.youtube.com/signin?action_handle_signin=true&nomobiletemp=1&hl=en_US&next=%2Findex&auth=";
        public static string YoutubeCommentUrl =                "http://www.youtube.com/comment_servlet?add_comment=1&comment_type=V&len=21&wc=5";
        public static string YoutubeAuthContinueUrl =           "http://www.youtube.com/signin?action_handle_signin=true&nomobiletemp=1&hl=en_US&next=%2Findex";
        public static string YoutubeCommentServerUrl =          "http://www.youtube.com/comment_servlet?all_comments=1&v=";

        CookieContainer cookieMonster = new CookieContainer();
        string UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.2.3) Gecko/20100401 Firefox/3.6.3";
        public string CookieDebug = "";

        public Communications()
        {
            System.Net.ServicePointManager.ServerCertificateValidationCallback += delegate(object sender,
                System.Security.Cryptography.X509Certificates.X509Certificate certificate,
                System.Security.Cryptography.X509Certificates.X509Chain chain,
                System.Net.Security.SslPolicyErrors sslPolicyErrors) 
                { return true; };
        }

        public ProxyInfo Proxy { get; set; }

        public class ProxyInfo
        {
            public string IP { get; set; }
            public string Port { get; set; }
            public string Username { get; set; }
            public string Password { get; set; }
        }

        public void ClearCookies()
        {
            cookieMonster = new CookieContainer();
        }

        void UpdateCookieDebug(string url)
        {
            CookieDebug = "";
            foreach (Cookie cookie in cookieMonster.GetCookies(new Uri(url)))
            {
                CookieDebug += cookie.Name + ": " + cookie.Value + Environment.NewLine;
            }
        }

        WebProxy GetProxy()
        {
            var proxy = new WebProxy(Proxy.IP, int.Parse(Proxy.Port));
            proxy.Credentials = new NetworkCredential(Proxy.Username, Proxy.Password);
            return proxy;
        }

        HttpWebRequest PrepareWebRequest(string url, string referer = "", string host = "", string accept = "")
        {
            UpdateCookieDebug(url);
            var request = HttpWebRequest.Create(url) as HttpWebRequest;
            request.CookieContainer = cookieMonster;
            request.UserAgent = UserAgent;
            request.AllowAutoRedirect = false;
            request.Proxy = GetProxy();
            if (referer != "") request.Referer = referer;
            if (host != "") request.Host = host;
            if (accept != "") request.Accept = accept;
            return request;
        }

        public string PerformGet(string url, string referer = "", string host = "", string accept = "")
        {
            var request = PrepareWebRequest(url, referer, host, accept);
            request.Method = "GET";

            try
            {
                var response = request.GetResponse();
                (response as HttpWebResponse).Cookies = cookieMonster.GetCookies(request.RequestUri);
                return new StreamReader(response.GetResponseStream()).ReadToEnd();
            }
            catch (Exception ex)
            {
                var a = ex;
            }
            return null;
        }

        public string PerformPost(string url, PostData postData, string referer = "")
        {
            var request = PrepareWebRequest(url, referer);
            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";

            byte[] bytes = Encoding.ASCII.GetBytes(postData.ToString());
            request.ContentLength = bytes.Length;
            request.GetRequestStream().Write(bytes, 0, bytes.Length);

            var response = request.GetResponse();
            (response as HttpWebResponse).Cookies = cookieMonster.GetCookies(request.RequestUri);
            return new StreamReader(response.GetResponseStream()).ReadToEnd();
        }

        public class PostData
        {
            private Dictionary<string, string> Values = new Dictionary<string, string>();

            public void AddValue(string key, string value)
            {
                Values.Add(key, HttpUtility.UrlEncode(value));
            }

            public override string ToString()
            {
                List<string> values = new List<string>();
                foreach (KeyValuePair<string, string> pair in Values)
                {
                    values.Add(pair.Key + "=" + pair.Value);
                }
                return string.Join("&", values.ToArray());
            }
        }
    }
}

